require 'json'

module SpreadsheetToJson
  # This is a class to load JSON file to spreadsheet
  class JsonToSheet
    attr_reader :spreadsheet
  
    def initialize(spreadsheet)
      @spreadsheet = spreadsheet
    end 
  
    # Load json to sheet
    def convert_json_to_sheet(json_file_path, sheet_name)
      arrays = json_to_hasharray(File.read(json_file_path))
      if arrays.count <= 0
        puts "the json file is empty"
        exit
      end
      worksheet = spreadsheet.get_sheet_by_name(sheet_name)
      worksheet.list.keys = arrays[0].keys
      arrays.each do |each|
        worksheet.list.push(each)
      end
      worksheet.save
    end
  
    private
    def json_to_hasharray(json_content)
      JSON.parse(json_content)
    end
  end
end
